<?php

namespace eqphp;
class http{

    //域内跳转
    static function redirect($url = null){
        header('Location: ' . U_R_L . $url);
        exit();
    }

    //异常终止并跳转
    static function abort($abort_message = '', $redirect_url = '', $wait_time = 10){
        $data = compact('abort_message', 'redirect_url', 'wait_time');
        util::with(new view())->assign($data)->display('abort/400');
        exit();
    }

    //完成、结束并终止并跳转
    static function success($tip_message = '', $redirect_url = '', $wait_time = 10){
        $data = compact('tip_message', 'redirect_url', 'wait_time');
        util::with(new view())->assign($data)->display('abort/200');
        exit();
    }

    //输出script
    static function script($data = null, $type = 'back_refresh', $is_exit = true){
        self::cross_domain();
        header('Content-Type:text/html; charset=utf-8');
        $script = html::script($data, $type);
        $is_exit && exit($script);
        echo $script;
    }

    //输出json,JSON_UNESCAPED_UNICODE
    static function json($data, $is_exit = true){
        self::cross_domain();
        header('Content-Type:application/json; charset=utf-8');
        $json = json_encode($data, JSON_UNESCAPED_UNICODE);
        $is_exit && exit($json);
        echo $json;
    }

    //输出xml
    static function xml($data, $root = 'rss', $is_exit = true){
        self::cross_domain();
        header('Content-Type:text/xml; charset=utf-8');
        $xml = '<?xml version="1.0" encoding="utf-8"?>';
        $xml .= "<{$root}>" . help::data_xml($data) . "</{$root}>";
        $is_exit && exit($xml);
        echo $xml;
    }

    //COOKIE设置
    static function cookie(){
        $param = func_get_args();
        list($key, $value) = $param;
        $expire = isset($param[2]) ? $param[2] : 2592000;
        $expire += time();

        $domain = system::config('system.domain.cookie');
        list($path, $secure, $only) = array('/', false, false);
        return setCookie($key, $value, $expire, $path, $domain, $secure, $only);
    }

    //构造post提交并获取接口返回数据
    static function curl($url, $data = null, $header = array(), $option = array()){
        $option += array('method' => 'post', 'timeout' => 10, 'in' => 'json', 'out' => 'json', 'tag' => 'item');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        if (defined('CURLOPT_SSL_VERIFYPEER')) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        }
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $option['timeout']);

        if (in_array($option['in'], array('xml', 'json', 'form'), true)) {
            $type = array(
                'xml' => 'Content-Type: text/xml',
                'json' => 'Content-Type: application/json',
                'form' => 'Content-type: application/x-www-form-urlencoded');
            array_push($header, $type[$option['in']] . '; charset=utf-8');
        }
        if ($header) {
            //'Cookie: '.http_build_query($_COOKIE,'','; ')
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }

        if ($option['method'] === 'post') {
            curl_setopt($ch, CURLOPT_POST, true);
        } else {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($option['method']));
        }
        if (is_array($data) && isset($option['in'])) {
            if ($option['in'] === 'json') {
                $data = json_encode($data, JSON_UNESCAPED_UNICODE);
            } elseif ($option['in'] === 'xml') {
                $data = help::data_xml($data, $option['tag']);
            } elseif ($option['in'] === 'form') {
                $data = urldecode(http_build_query($data));
            }
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            logger::exception('curl', curl_errno($ch) . ': ' . curl_error($ch));
            //$response = substr($response, curl_getinfo($ch, CURLINFO_HEADER_SIZE));
        }

        curl_close($ch);
        if ($option['out'] === 'json') {
            return json_decode($response, true);
        } elseif ($option['out'] === 'xml') {
            return simplexml_load_string($response);
        }
        return $response;
    }

    //websocket推送
    static function socket(array $data){
        $socket = config('socket');
        $address = 'tcp://' . $socket['address'];
        $handle = stream_socket_client($address, $error_no, $error_message, 3);
        if ($error_no || strlen($error_message)) {
            logger::exception('socket', $error_no . ': ' . $error_message);
            return false;
        }
        $data['secure_key'] = $socket['secure_key'];
        fwrite($handle, json_encode($data) . PHP_EOL);
        fread($handle, 1);
        return true;
    }

    //发送http错误头信息
    static function send($code = 404, $is_out = true, $is_exit = true){
        $message = util::meta('http_status.' . $code);
        if (strlen($message)) {
            header('HTTP/1.1 ' . $code . ' ' . $message);
            header('Status:' . $code . ' ' . $message);
            if ($is_out) {
                //echo $code . ' ' . $message;
                smarty()->display('abort/' . $code);
            }
            $is_exit && exit();
        }
    }

    //判断是否异步请求
    static function is_ajax(){
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
            $x_requested = strtolower($_SERVER['HTTP_X_REQUESTED_WITH']);
            if ($x_requested === 'xmlhttprequest') {
                return true;
            }
        }
        return false;
    }

    static function cross_domain(){
        //if (ob_get_level() !== 0 && ob_end_clean() === false) {
        //    ob_clean();
        //}
        if (headers_sent($file, $line)) {
            exit('error head :' . $file . $line);
        }
        if (system::config('system.domain.is_cross')) {
            header('Access-Control-Allow-Origin: *');
            header('Access-Control-Allow-Headers: Token, Content-Type, Range, If-Match');
            header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD');
        }
    }

}